const guideData = require('../../utils/guideData.js');
const pageBehavior = require('../../utils/pageBehavior');
const { debounce } = require('../../utils/common');

Page({
  behaviors: [pageBehavior],

  data: {
    categories: guideData.categories,
    guides: guideData.guides,
    activeCategory: 'all',
    searchKeyword: '',
    showSearch: false,
    filteredGuides: guideData.guides
  },

  onLoad() {
    this.filterGuides();
  },

  onShow() {
    this.updateTabBar(2);
  },

  // 切换分类
  onCategoryChange(e) {
    const category = e.currentTarget.dataset.category;
    if (category === this.data.activeCategory) {
      return;
    }
    this.setData({ activeCategory: category });
    this.filterGuides();
  },

  // 筛选指南
  filterGuides() {
    const { activeCategory, searchKeyword, guides } = this.data;
    let filtered = guides;

    // 按分类筛选
    if (activeCategory !== 'all') {
      filtered = filtered.filter(guide => guide.category === activeCategory);
    }

    // 按搜索关键词筛选（支持标题、摘要、标签、内容搜索）
    if (searchKeyword && searchKeyword.trim()) {
      const keyword = searchKeyword.trim().toLowerCase();
      filtered = filtered.filter(guide => 
        guide.title.toLowerCase().includes(keyword) ||
        guide.summary.toLowerCase().includes(keyword) ||
        (guide.content && guide.content.toLowerCase().includes(keyword)) ||
        (guide.tags && guide.tags.some(tag => tag.toLowerCase().includes(keyword)))
      );
    }

    // 排序：热门优先，然后按id排序
    filtered.sort((a, b) => {
      if (a.isPopular !== b.isPopular) {
        return b.isPopular - a.isPopular;
      }
      return a.id - b.id;
    });

    this.setData({ filteredGuides: filtered });
  },

  // 搜索相关方法
  toggleSearch() {
    const newShowSearch = !this.data.showSearch;
    this.setData({ showSearch: newShowSearch });
    if (!newShowSearch) {
      this.setData({ searchKeyword: '' });
      this.filterGuides();
    }
  },

  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });
    this.debouncedFilter();
  },

  // 使用防抖函数
  debouncedFilter: debounce(function() {
    this.filterGuides();
  }, 300),

  onSearchConfirm() {
    this.filterGuides();
  },

  clearSearch() {
    this.setData({ searchKeyword: '' });
    this.filterGuides();
  },

  // 收藏功能
  toggleFavorite(e) {
    const id = e.currentTarget.dataset.id;
    const guides = this.data.guides.map(guide => {
      if (guide.id === id) {
        return { ...guide, isFavorite: !guide.isFavorite };
      }
      return guide;
    });

    this.setData({ guides });
    this.filterGuides();

    const guide = guides.find(g => g.id === id);
    this.showSuccess(guide.isFavorite ? '已收藏' : '取消收藏');
  },

  // 查看指南详情
  viewGuide(e) {
    const guide = e.currentTarget.dataset.guide;
    
    // 更新阅读进度（增加50%）
    const guides = this.data.guides.map(g => {
      if (g.id === guide.id) {
        const newProgress = Math.min(g.readProgress + 50, 100);
        return { ...g, readProgress: newProgress };
      }
      return g;
    });
    
    this.setData({ guides });
    this.filterGuides();

    // 格式化内容显示
    let displayContent = guide.content || guide.summary;
    // 移除Markdown格式符号，但保留重要标记
    displayContent = displayContent
      .replace(/\*\*(.+?)\*\*/g, '$1') // 移除粗体标记，保留内容
      .replace(/```[\s\S]*?```/g, '') // 移除代码块
      .trim();
    
    // 如果内容太长，截取前800字显示
    if (displayContent.length > 800) {
      displayContent = displayContent.substring(0, 800) + '\n\n...（内容较长，建议仔细查看完整内容）';
    }
    
    // 显示指南内容
    this.showConfirm({
      title: guide.title,
      content: displayContent,
      confirmText: '已读完',
      cancelText: guide.isFavorite ? '取消收藏' : '收藏'
    }).then((confirmed) => {
      if (confirmed) {
        // 标记为已读
        const updatedGuides = this.data.guides.map(g => {
          if (g.id === guide.id) {
            return { ...g, readProgress: 100 };
          }
          return g;
        });
        this.setData({ guides: updatedGuides });
        this.filterGuides();
        this.showSuccess('已标记为已读');
      } else {
        // 点击收藏/取消收藏
        this.toggleFavorite({ 
          currentTarget: { 
            dataset: { id: guide.id } 
          } 
        });
      }
    });
  },

  // 错误处理
  retryLoad() {
    this.filterGuides();
  }
});